<?php
/**
 * Created by PhpStorm.
 * User: wangsentao
 * Date: 2018/3/8
 * Time: 上午9:13
 */

namespace app\common\Utils;

use app\api\controller\Errorcode;
use app\api\controller\Fun;
use app\api\repository\OrderRespository;
use app\api\repository\OrderInfoShaohuoRepository;
use app\common\Model\UserBalance;
use app\api\service\ShaohuoOrderService;
use app\common\ShaoHuoPay\Exceptions\Exception;
use think\Db;
use app\api\service\JpushService;
use app\api\repository\PayLogRespository;


class BalancePay
{
    /**
     * 用户余额支付
     * 扣掉余额
     * 添加支付流水
     * @param $uid
     * @param $goods_fell
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function pay($uid, $order_info)
    {

        $userbalance = model("app\common\Model\UserBalance");

        $res = $userbalance->where('uid', $uid)->find();

        if ($res == null) {
            UserBalance::createUserWallet($uid);
        }
        # 标记支付钱包类型 0 余额支付 1 提现月支付
        $pay_type_flag = 0;
        #判断用户余额
        if ($res->recharge_balance < $order_info['shipping_fee']) {
            #使用可提现余额支付 退款的时候退到用户的余额
            if($res->withdraw_balance < $order_info['shipping_fee']){
                return Fun::error( '500001','');
            }
            # 提现余额支付
            $pay_type_flag = 1;
        }

        Db::startTrans();

        try {

            //计算用户余额( 用户余额部分 ，充值的部分)
            if($pay_type_flag == 0){
                $userbalance->recharge_balance = $res->recharge_balance - $order_info['shipping_fee'];
            }
            # 计算用户提现余额
            if($pay_type_flag == 1){
                $userbalance->withdraw_balance = $res->withdraw_balance - $order_info['shipping_fee'];
            }

            $userbalance->where('uid', $uid);
            $userbalance->isUpdate(true)->save();

            //更新主订单
            OrderRespository::instance()->updateOrderPayedStatus($order_info['order_num'],'','');

            //更新捎货订单信息
            OrderInfoShaohuoRepository::instance()->updateOrderPayedStatus($order_info['order_num'],'','');

            //更新流水记录
            PayLogRespository::instance()->updateOrderPayedStatus($order_info['order_num'], '', $res->recharge_balance + $res->withdraw_balance - $order_info['shipping_fee']);

            //更新捎货物流
            ShaohuoOrderService::instance()->orderAction($order_info['order_id'],2,$uid,'');

            //极光推送订单
            JpushService::instance()->makeOrder($order_info['order_id']);

            Db::commit();
            //订单支付成功
            $data = UserBalance::getUserBalance($uid);
            $wallet['uid'] = $data['uid'];
            $wallet['recharge_balance'] = $data['recharge_balance'] / config('convert_unit');
            $wallet['withdraw_balance'] = $data['withdraw_balance'] / config('convert_unit');
            $wallet['frozen_balance'] = $data['frozen_balance'] / config('convert_unit');
            $wallet['total_balance'] = $wallet['recharge_balance'] + $wallet['withdraw_balance'];
            return Fun::success($wallet,'订单支付成功');

        } catch (\Exception $e) {
            Db::rollback();
            return Fun::error( '111111',$e->getMessage());
        };

    }

    /**
     * 退款
     */
    public static function refound($order_info)
    {

        $_order_info = Db::table('sh_order_info_shaohuo')->where('order_id',$order_info['id'])->field('order_num,uid,shipping_fee')->find();
        Db::startTrans();

        try {
            # 修改账户的余额
            $userbalance = model('app\common\Model\UserBalance');
            $res = $userbalance->where('uid',$_order_info['uid'])->find();

            $userbalance->recharge_balance = $res->recharge_balance + $_order_info['shipping_fee'];

            $userbalance->where('uid', $_order_info['uid']);
            $userbalance->isUpdate(true)->save();

            # 添加pay_log 日志
            PayLogRespository::instance()->createPayLog(
                $_order_info['uid'],
                $_order_info['order_num'],
                1,
                5,
                0,
                $_order_info['shipping_fee'] // 单位为分 消费为负数
            );
            Db::commit();
            return ['code'=>'success','msg'=>'退款成功'];
        }catch (Exception $exception){
            Db::rollback();
            return [
                'code' => 'fail',
                'msg'=> $exception->getMessage(),
            ];
        }

    }
}